/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024. All rights reserved.
 *
 */

import path from 'path';

import {expect} from '@jest/globals';
import * as fse from 'fs-extra';

import {initExecuteCommand, runHvigorAsync} from '../../common/common';
import {addOhPackageDps, commonFileOperation, commonJson5Operation} from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from '../../plugins/project-builder/models/constants';
import {Project} from '../../plugins/project-builder/models/project-models';
import {ICaseRecord} from '../../plugins/report-builder/report-models';
import {TestCaseBuilder} from '../../plugins/task-builder/task-case-builder';
import {ProjectBuildOption, TestCaseFun} from '../../plugins/task-builder/test-case';
import {TestTaskOption, TestTaskOptionBuilder} from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: [ModuleTemplateType.StaticLibrary]
};

/**
 * @param {Project} project
 * @param {TestTaskOption} taskConfig
 * @param {ICaseRecord} record
 * @return res
 */
const testFun: TestCaseFun = async (project: Project, taskConfig: TestTaskOption, record: ICaseRecord) => {
  const projectRoot = project.projectRootPath();

  // 修改工程 build-profile.json5 的 strictMode 信息
  await commonJson5Operation(path.resolve(projectRoot, 'build-profile.json5'), async (json5) => {
    json5.app.products[0].buildOption = {
      strictMode: {
        caseSensitiveCheck: true,
        useNormalizedOHMUrl: false
      }
    };
  });

  const libraryPath = path.resolve(projectRoot, 'staticLibrary');

  /**
   * 修改 StaticLibrary 模块生成 Har 包
   * 1、Index.ets 增加并导出 add 函数
   * 2、oh-package.json5 增加 packageType 字段
   * 3、开启混淆，构建 release har 包
   */
  // 修改 Index.ets 文件，增加并导出 add 函数
  await commonFileOperation(path.resolve(libraryPath, 'Index.ets'), async (buffer) => {
    const content = buffer.toString();
    return `export function add() {return 'add'}\n${content}`;
  });

  // 增加 packageType 字段; 正常 Static Library 模块没有这个字段
  await commonJson5Operation(path.resolve(libraryPath, 'oh-package.json5'), async (json5) => {
    json5.packageType = 'InterfaceHar';
  });

  // 构建 release har 包
  const assembleHarCmd = initExecuteCommand({
    mode: 'module',
    module: 'staticLibrary@default',
    product: 'default',
    tasks: 'assembleHar',
    buildMode: 'release',
  });

  const assembleHarResult = await runHvigorAsync(projectRoot, assembleHarCmd);
  record.addStep('编译构建 staticLibrary 模块生成har', assembleHarResult);
  expect(assembleHarResult.stdout).toContain('BUILD SUCCESSFUL');

  /**
   * 修改 entry 模块生成 hap 包
   * 1、修改 oh-package.json5 增加依赖
   * 2、修改 pages/Index.ets 引用 add 函数
   * 3、构建 hap 包
   */
  const entryPath = project.getModule('entry').moduleRootPath();
  // 复制 staticLibrary.har 到 entry 目录下
  await fse.copyFile(path.resolve(libraryPath, 'build', 'default', 'outputs', 'default', 'staticLibrary.har'),
    path.resolve(entryPath, 'staticLibrary.har'));

  // 修改 oh-package.json5 增加依赖 "library": "file:staticLibrary.har"
  await addOhPackageDps(entryPath, {'library': 'file:staticLibrary.har'});

  await commonFileOperation(path.resolve(entryPath, 'src/main/ets/pages/Index.ets'), async (buffer) => {
    const content = buffer.toString();
    return `import { add } from 'library';\nadd();\n${content}`;
  });

  const commands = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap'
  });

  const result = await runHvigorAsync(projectRoot, commands);
  record.addStep('执行编译构建', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
};

TestCaseBuilder.builder()
  .caseName('DTS2024101108728')
// eslint-disable-next-line max-len
  .description('【DevEco Studio】【开发自提单】【功能】nativeResolver开启下当har模块配置有main字段和packageType:InterfaceHar时编译出错')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.DTS).build())
  .testFun(testFun)
  .load();
